#include<stdio.h>
#include "../include/vfs.h"
#include<stdlib.h>
#include<string.h>


int listfile(char path[], char filepath[])
{
		
		FD* fd;
		FILE *fp,*add;
		int i,saveblock,k=0;
		char *data,ch,*tok;
		
		Block* b;
		
		fd=(FD*)malloc(sizeof(FD));
		strcpy(fd->path,path);
		header=(Header*)malloc(sizeof(Header));
		b=(Block*) malloc(sizeof(Block));

		//tok = strrchr(path,'.');


		/*if(strcmp(tok,".txt")!=0)
			return 5;
		*/

		if(strcmp(filepath," ")==0)
			return 4;

		if(strcmp(path," ")==0)
			return 3;
		
		fp=fopen(filesystem_name, "r+b");
		fread(header,sizeof(Header),1,fp);

		add = fopen(filepath,"a");

		if(add==NULL)
			return 2;


		data = malloc(1024*sizeof(char));
		
		
		fd = search(roots.naryroot,fd);

		if(fd==NULL)
		{
			
			return 1;
		}

		if(fd->file_type==0){

			return 1;
			
		}	
		else
		{
			saveblock=fd->block_no;

		
			for(i=0;i<header->num_blocks;i++)
			{
				fread(b,sizeof(Block),1,fp);
			
				if (b->num==saveblock)					
				{
					strcpy(data,b->buffer);
					
					break;
				}
			}

			k=strlen(data);
			i=0;
		
			fseek(add,0,SEEK_END);
			fprintf(add,"\nCONTENTS: %s\n ",fd->filename);

			while(k)
			{
				ch=data[i];
				fputc(ch,add);
				k--;
				i++;
			}

		}
			
	rewind(fp);
	fwrite(header,sizeof(Header),1,fp);

	fclose(fp);
	fclose(add);
		
	return 0;

}



